package edu.ahut.corejava2;
//-  实现分数类（支持+ - * /和排序)，计算出 1/1+1/2+....+1/20的精确值（应该化简为最简分数）
public class Exp01SumFractions {
    public static void main(String[] args) {
        Fraction f2=new Fraction(0,-6);
        System.out.println(f2);//f.toString()

        Fraction sum = new Fraction();
        for (int i = 1; i <= 20; i++) {
            Fraction f = new Fraction(1, i);
            sum = sum.add(f);
        }
        System.out.println(sum);
    }

    static class Fraction {
        private long up;
        private long down;

        public Fraction() {
            this(0, 1);
        }

        @Override
        public String toString() {
            return String.format("%d/%d", up, down);

        }

        /**
         * 分数化简算法(核心逻辑）
         * 1. 如果同号则都转为正数
         * 2. 否则分子是负数，而分母永远是正数
         * 3. 0 约定为0/1
         * 4. 最终都要消去最大公因子
         */
        private void rationalize() {
            if (up * down < 0) {
                up = -Math.abs(up);
                down = Math.abs(down);
            } else {
                up = Math.abs(up);
                down = Math.abs(down);
            }
            long g = gcd(Math.abs(up), down);
            up /= g;
            down /= g;
        }

        private long gcd(long a, long b) {
            return b == 0 ? a : gcd(b, a % b);
        }

        public Fraction(long up, long down) {
            this.up = up;
            this.down = down;
            rationalize();
        }

        public Fraction add(Fraction that) {
            long up = this.up * that.down + this.down * that.up;
            long down = this.down * that.down;
            return new Fraction(up, down);
        }

    }
}
